<?php

declare(strict_types=1);

namespace App\Common\Service;

use App\Common\Interfaces\ProxyIpInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Codec\Packer\JsonPacker;
use Hyperf\Contract\PackerInterface;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProxyIpService implements ProxyIpInterface
{

    protected Client $client;

    protected PackerInterface $packer;

    #[Inject]
    protected Redis $redis;

    public string $proxyType = 'LONG';

    public function __construct(PackerInterface $packer = null)
    {
        $handler = null;
        if (Coroutine::inCoroutine()) {
            $handler = new CoroutineHandler();
        }
        $this->client = new Client([
            'base_uri' => 'http://api.tianqiip.com',
            'timeout' => 3,
            'handler' => $handler,
        ]);
        $this->packer = $packer ?? new JsonPacker();
    }

    /**
     * 获取短效代理ip地址
     * @param string $proCode 省份编码
     * @param string $cityCode 城市编码
     * @return mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getShortProxyIp(string $proCode, string $cityCode = ''): mixed
    {
        $key = 'proxy_info'.$proCode.$cityCode;

        $cache = $this->redis->get($key);
        if(!$cache){
            !$cityCode && $cityCode = $proCode;
            $url = "/getip?secret=gta9zqkr&type=json&num=1&region={$cityCode}&cs=1&ys=1&ts=1&time=3&port=1&sign=f869c5ea0f639074c4a4d0e6b2f41b68";

            try {
                $response = $this->client->get($url);
                $res = $this->packer->unpack((string) $response->getBody());
                logger()->info("__机器人{$cityCode}获取短效代理IP返回:".json_encode($res));
                if($res['code'] == 1000 && $res['data'][0]['ip']){
                    $this->proxyType = 'SHORT';
                    //设置类型为短效
                    $cache = "socks5://2yvgy5:lx3rakve@{$res['data'][0]['ip']}:{$res['data'][0]['port']}";
                    $this->redis->set($key, $cache,3* 60);
                }else{
                    $cache = '';
                }
            } catch (GuzzleException $e) {
                logger()->error("__机器人{$cityCode}获取短效代理IP异常:".$e->getMessage());
                $cache = '';
            }
        }
        return $cache;
    }

}